<template>
  <div class="task-management-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="任务名称">
          <el-input
            v-model="queryParams.taskName"
            placeholder="请输入任务名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="queryParams.taskType" placeholder="请选择任务类型" clearable style="width: 240px;">
            <el-option
              v-for="item in taskTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable style="width: 240px;">
            <el-option label="待执行" value="0" />
            <el-option label="执行中" value="1" />
            <el-option label="已完成" value="2" />
            <el-option label="失败" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd" :icon="Plus">添加任务</el-button>
        <el-button 
          type="success" 
          @click="handleBatchExecute(selectedRows)" 
          :icon="VideoPlay"
          :disabled="selectedRows.length === 0"
        >
          批量执行
        </el-button>
        <el-button 
          type="danger" 
          @click="handleBatchDelete(selectedRows)" 
          :icon="Delete"
          :disabled="selectedRows.length === 0"
        >
          批量删除
        </el-button>
      </div>
    </el-card>

    <!-- 任务列表 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="taskList"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="任务ID" width="100" />
        <el-table-column prop="taskName" label="任务名称" min-width="150" />
        <el-table-column prop="deviceName" label="设备名称" width="100" />
        <el-table-column prop="taskType" label="任务类型" width="120" />
        <el-table-column prop="parameters" label="优化参数" min-width="200">
          <template #default="{ row }">
            <el-tooltip :content="formatParameters(row.parameters)" placement="top">
              <span class="parameters-text">{{ formatParameters(row.parameters) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="任务状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusDisplay(row.status).type">
              {{ getStatusDisplay(row.status).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="executeTime" label="执行时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.executeTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 0" 
              type="success" 
              link 
              @click="handleExecute(row.id)" 
              :icon="VideoPlay"
            >
              执行
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)" :icon="Edit">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row.id)" :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 任务表单对话框 -->
    <el-dialog
      v-model="formVisible"
      :title="taskForm.id ? '编辑任务' : '添加任务'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="taskForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="taskForm.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="taskForm.deviceType" placeholder="请选择设备类型" @change="handleDeviceTypeChange">
              <el-option
                v-for="option in deviceTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择设备" prop="deviceId">
            <el-select
              v-model="selectedDevice"
              placeholder="请先选择设备类型"
              filterable
              :loading="deviceLoading"
              :disabled="!taskForm.deviceType"
              @change="handleDeviceChange"
              value-key="id"
            >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
              <el-option
                v-for="device in deviceList"
                :key="device.id"
                :label="`${device.name} (ID: ${device.id})`"
                :value="device"
              >
                <div class="device-option">
                  <div>{{ device.name }}</div>
                  <div class="device-info">ID: {{ device.id }}</div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="taskForm.taskType" placeholder="请选择任务类型" style="width: 100%">
            <el-option
              v-for="item in taskTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优化参数" prop="parameters">
          <el-input
            v-model="taskForm.parameters"
            type="textarea"
            placeholder="请输入JSON格式的优化参数，示例已自动填充"
            :rows="3"
          />
          <div class="form-tip">
            <small>可配置的参数包括：frequency(频率), power(功率), channel(信道), bandwidth(带宽), beamforming(波束成形)</small>
          </div>
        </el-form-item>
        <!-- 任务状态默认为待执行，无需用户选择 -->
        <el-form-item label="任务状态" prop="status" v-show="false">
          <el-input v-model="taskForm.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="formLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete, Edit, VideoPlay } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useTask } from '../hooks/useTask'

// 使用任务管理hooks
const {
  taskList,
  loading,
  total,
  queryParams,
  taskForm,
  formVisible,
  formLoading,
  taskTypeOptions,
  deviceTypeOptions,
  deviceList,
  deviceLoading,
  selectedDevice,
  fetchTaskList,
  handleSearch,
  handleReset,
  handleAdd,
  handleEdit,
  handleSubmit,
  handleDelete,
  handleBatchDelete,
  handleExecute,
  handleBatchExecute,
  getStatusDisplay,
  formatParameters,
  handleDeviceTypeChange,
  handleDeviceChange
} = useTask()

// 选择的行
const selectedRows = ref([])

// 表单验证规则
  // 表单验证规则
  const formRules = {
    taskName: [
      { required: true, message: '请输入任务名称', trigger: 'blur' }
    ],
    deviceType: [
      { required: true, message: '请选择设备类型', trigger: 'change' }
    ],
    deviceId: [
      { required: true, message: '请选择设备', trigger: '' }
    ],
    taskType: [
      { required: true, message: '请选择任务类型', trigger: 'change' }
    ],
    parameters: [
      { 
        required: true, 
        message: '请输入优化参数', 
        trigger: 'blur' 
      },
      {
      validator: (rule, value, callback) => {
        if (value) {
          try {
            JSON.parse(value)
            callback()
          } catch (e) {
            callback(new Error('参数格式不正确，请输入有效的JSON格式'))
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.size = size
  queryParams.page = 1
  fetchTaskList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchTaskList()
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchTaskList()
})
</script>

<style scoped>
.task-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
  .form-tip {
    margin-top: 8px;
    color: #606266;
    font-size: 12px;
  }
  
  .parameters-text {
    display: inline-block;
    max-width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    cursor: pointer;
  }
  
  .device-option {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }
  
  .device-info {
    font-size: 12px;
    color: #606266;
  }
</style>